<!--
 * @Author: suoyue 445484430@qq.com
 * @Date: 2022-07-04 16:58:14
 * @LastEditors: suoyue 445484430@qq.com
 * @LastEditTime: 2022-07-08 00:10:32
 * @FilePath: \server\test\upload.html
 * @Description: 实现了上传的前端接口
 * 
 * Copyright (c) 2022 by suoyue 445484430@qq.com, All Rights Reserved. 
-->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="add">
        <p>商品名称： <input type="text" id="productName" title="name" name="name"></p>
        <p>商品图片： <input id="file" type="file" class="file" title="file" name="file"></p>
        <p><button id="add-btn">添加商品</button></p>
        <p id="info"></p>
        <img id="image-preview" src="" alt="123" />
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">

        // 新建表单数据对象，用来存储上传的文件及上传的其它数据
        let param = new FormData()
        let file;
        $(".file")[0].onchange = function () {
            console.log(".file")
            //获取图片信息
            file = this.files[0]
        }
        $("#add-btn").click(function () {
            console.log("upload....")
            let productName = $("#productName")[0].value;
            param.append("name", productName)
            console.log(param)
            
            // 通过FormData生成服务端需要的数据格式
            let data = new FormData();
            data.append("file", file);
            data.append("name",productName)

            // 进行异步请求
            axios({
                method: 'POST',
                url: 'http://127.0.0.1:6001/api/user/changeAvatar',
                data,
                headers: { "Content-Type": "multipart/form-data", "authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTEsIm5hbWUiOiJhZG1pbiIsImlhdCI6MTY1NzIwNzA2OSwiZXhwIjoxNjU3MjEwNjY5fQ.HtUwn2qqe7nRsMuLylN_VDcjWKLbwieYypZLWRt2kIg"}
            }).then(res => {
                console.log(res.data)
            })

        }
        )

        let fileInput = document.getElementById('file');
        let info = document.getElementById('info');
        let preview = document.getElementById('image-preview');
        // 监听change事件:
        fileInput.addEventListener('change', function () {
            // 清除背景图片:
            preview.style.backgroundImage = '';
            if (!fileInput.value) {
                info.innerHTML = '没有选择文件';
                return;
            }
            let file = fileInput.files[0];
            let size = file.size;
            if (size >= 10 * 1024 * 1024) {
                alert('文件大小超出限制');
                info.innerHTML = '文件大小超出限制';
                return false;
            }
            // 获取File信息:
            info.innerHTML = `文件名称:  + ${file.name}<br>文件大小: ${file.size} <br>上传时间: ${file.lastModifiedDate}`;
            if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
                alert('不是有效的图片文件!');
                return;
            }
            // 读取文件:
            let reader = new FileReader();
            reader.onload = function (e) {
                let data = e.target.result;
                console.log(preview, 'a标签')
                preview.src = data
            };
            // 以DataURL的形式读取文件:
            reader.readAsDataURL(file);

            //"file"为前后端约定vb的属性名
            param.append("file", file)

        });

        function save() {

            var url = preview.src; // 获取图片地址
            var a = document.createElement('a'); // 创建一个a节点插入的document
            var event = new MouseEvent('click') // 模拟鼠标click点击事件
            a.download = 'beautifulGirl' // 设置a节点的download属性值
            a.href = url; // 将图片的src赋值给a节点的href
            a.dispatchEvent(event)
        }
    </script>
</body>

</html>